package cn.ymjr.sys.util;

import cn.ymjr.sys.config.exception.BusinessException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author Tiny
 * @create 2022/3/30 15:13
 */
public class NameChangeUtil {


    public static String getPinyin(char name)throws BusinessException{
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        String result = "";
        try {
            if(Character.toString(name).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
                String[] temp = PinyinHelper.toHanyuPinyinStringArray(name,format);
                result = temp[0];
            }else{
                throw new BusinessException("请输入正确的姓名");
            }
        }catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getPinyin(String name)throws BusinessException {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = name.trim().toCharArray();
        String result = "";
        try {
            for (int i=0;i<arrays.length;i++) {
                char ti = arrays[i];
                if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,format);
                    result += temp[0];
                }else{
                    throw new BusinessException("请输入正确的姓名");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
